package com.xreal.netty.client;

import com.xreal.netty.client.handler.CustomClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author yangzhongming
 * @desc netty 客户端示例
 * @date 2022/6/14
 */
@SuppressWarnings("unused")
public class NettyClient {

    //服务端地址
    private final String host;
    //服务端端口
    private final int port;

    public NettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     * 连接服务端
     */
    public void connect() {
        NioEventLoopGroup executors = null;
        try {
            //创建客户端处理线程
            executors = new NioEventLoopGroup();

            //创建客户端连接对象
            Bootstrap client = new Bootstrap();

            //设置属性
            client.group(executors)
                    //客户端连接通道类型
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //责任链模式--添加处理器
                            socketChannel.pipeline().addLast(new CustomClientHandler());
                        }
                    });
            System.out.println("客户端准备就绪：远程地址：" + this.host + " ,远程端口：" + this.port);
            //连接服务器端
            ChannelFuture channelFuture = client.connect(this.host, this.port).sync();
            //关闭监听
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (executors != null) {
                executors.shutdownGracefully();
            }
        }
    }
}
